package leetcode.code0211;

import java.util.ArrayList;
import java.util.List;

public class WordTreeNode {

	WordTreeNode[] branch;
	boolean isEnd;

	public WordTreeNode() {
		this.branch = new WordTreeNode[26];
		this.isEnd = false;
	}

	public void addWord(char[] words) {
		int c = words[0] - 'a';
		WordTreeNode root = this.branch[c];
		if (root == null) {
			root = new WordTreeNode();
			this.branch[c] = root;
		}
		for (int i = 1; i < words.length; i++) {
			c = words[i] - 'a';
			if (root.branch[c] == null) {
				root.branch[c] = new WordTreeNode();
			}
			root = root.branch[c];
		}
		root.isEnd = true;
	}

	public boolean search(char[] words) {
		int c = words[0] - 'a';
		WordTreeNode root = this.branch[c];
		if (root == null) {
			return false;
		}
		for (int i = 1; i < words.length; i++) {
			c = words[i] - 'a';
			if (root.branch[c] == null) {
				return false;
			}
			root = root.branch[c];
		}
		return root.isEnd;
	}

	public List<WordTreeNode> branchList() {
		List<WordTreeNode> ans = new ArrayList<>();
		for (WordTreeNode wtn : this.branch) {
			if (wtn != null) {
				ans.add(wtn);
			}
		}
		return ans;
	}
}
